import { NextResponse } from "next/server";
import productModule from "@/modules/product";
import pool from "@/lib/db";
import generateSlugify from "@/utils/generateSlugify";

export async function GET(request) {

  const { searchParams } = new URL(request.url);
  const codeMap = { 0: '获取成功', 1: '内容为空' };
  const limit = parseInt(searchParams.get('limit') || 10);
  const page = parseInt(searchParams.get('page') || 1);
  const offset = (page - 1) * limit;
  const res = await productModule.getAll(limit, offset);
  if (!res) { return NextResponse.json({ code: 1, codeMap, message: "No products found" }); }
  return NextResponse.json({ code: 0, codeMap, message: "success", data: res.products, total: res.total });
}

export async function POST(request) {
  const codeMap = { 0: '创建成功', 1: '标题不能为空', 2: '创建失败' };
  const { title, description } = await request.json();
  if (!title) { return NextResponse.json({ code: 1, codeMap, message: 'Title cannot be empty' }); }
  const product = await productModule.create({ status: 1, title, description, price: 0, compare_price: 0, stock: 0, cover: '', sort: 0, template: 'default', slug: null, meta_title: '', meta_description: '' });
  if (!product) { return NextResponse.json({ code: 2, codeMap, message: 'Create failed' }); }
  return NextResponse.json({ code: 0, codeMap, message: 'Success', id: product.insertId });
}

export async function DELETE(request) {
  const { id } = await request.json();
  const codeMap = { 0: '删除成功', 1: '产品不存在', 2: "删除失败" };
  const isHas = await productModule.getById(id);
  if (!isHas) { return NextResponse.json({ code: 1, codeMap, message: 'No product found' }); }
  const result = await productModule.deleteById(id);
  if (result.affectedRows === 0) { return NextResponse.json({ code: 2, codeMap, message: 'Delete failed' }); }
  return NextResponse.json({ code: 0, codeMap, message: 'Delete success' });
}

export async function PUT(request) {
  const codeMap = { 0: '更新成功', 1: 'Id为空', 2: '产品不存在', 3: '标题不能为空', 4: '更新失败' };
  const { product } = await request.json();
  const { id, title, slug: originSlug, } = product;
  if (!id) { return NextResponse.json({ code: 1, codeMap, message: 'Product ID is required' }); }
  const data = productModule.getById(id);
  if (!data) { return NextResponse.json({ code: 1, codeMap, message: 'No product found' }); }
  if (title === '' || !title) { return NextResponse.json({ code: 1, codeMap, message: 'Title cannot be empty' }); }
  const slugList = await productModule.getSlugs();
  const slug = !originSlug ? await generateSlugify(title, slugList) : originSlug;
  const updateResult = await productModule.update(id, { ...product, slug });
  if (updateResult.affectedRows === 0) { return NextResponse.json({ code: 4, codeMap, message: 'Update failed' }); }
  return NextResponse.json({ code: 0, codeMap, message: 'Update success' });
}

export async function PATCH(request) {
  const codeMap = { 0: '更新成功', 1: '更新type为空或不是指定类型', 2: '产品不存在', 3: '旧图片删除失败', 4: '新图片插入失败', 5: '更新失败', 6: '删除旧Collections失败', 7: '没有需要添加的Collections', 8: '添加Collections失败' };
  const { product_id, data, type } = await request.json();
  if (type === 'images') {
    const conn = await pool.getConnection();
    try {
      await conn.beginTransaction();
      const product = await productModule.getById(product_id, conn);
      if (!product) {
        await conn.rollback();
        return NextResponse.json({ code: 2, codeMap, message: 'No product found' });
      }
      const productImages = await productModule.getImagesById(product_id, conn);
      if (productImages.length > 0) {
        const deleteResult = await productModule.deleteImagesById(product_id, conn);
        if (deleteResult === 0) {
          await conn.rollback();
          return NextResponse.json({ code: 3, codeMap, message: 'Delete old images failed' });
        }
      }
      const insertImages = productModule.createImages(product_id, data, conn);
      if (!insertImages) {
        await conn.rollback();
        return NextResponse.json({ code: 2, codeMap, message: 'Update failed' });
      }
      await conn.commit();
      return NextResponse.json({ code: 0, codeMap, message: 'Update success' });
    } catch (error) {
      await conn.rollback();
      return NextResponse.json({ code: 2, codeMap, message: 'Update failed' });
    } finally {
      conn.release();
    }
  } else if (type === 'collections') {
    const conn = await pool.getConnection();
    try {
      await conn.beginTransaction();
      if (!product_id || !data) {
        await conn.rollback();
        return NextResponse.json({ code: 1, codeMap, message: 'Product ID or data is required' });
      }
      const product = await productModule.getAllInformationById(product_id, conn);
      if (product.collections.length > 0) {
        const deleteResult = await productModule.deleteCollectionsById(product_id, conn);
        if (deleteResult === 0) {
          await conn.rollback();
          return NextResponse.json({ code: 3, codeMap, message: 'Delete old collections failed' });
        }
      }
      if (data.length === 0) {
        await conn.commit();
        return NextResponse.json({ code: 0, codeMap, message: 'No collections to add' });
      }
      const insertCollections = await productModule.createCollections(product_id, data.map(c => c.id), conn);
      if (!insertCollections) {
        await conn.rollback();
        return NextResponse.json({ code: 8, codeMap, message: 'Insert new collections failed' });
      }
      await conn.commit();
      return NextResponse.json({ code: 0, codeMap, message: 'Update success' });
    } catch (error) {
      console.log(error);
      await conn.rollback();
      return NextResponse.json({ code: 5, codeMap, message: 'Update failed' });
    } finally {
      conn.release();
    }
  } else {
    return NextResponse.json({ code: 5, codeMap: { 1: 'Invalid type' }, message: 'Invalid type' });
  }
}